package com.dobest.alipaywool;

import com.dobest.alipaywool.model.SmsConfig;
import com.dobest.alipaywool.phone.PhoneGenerator;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.util.Set;

/**
 * @author: hujiansong
 * @since: 2018/12/4 14:21
 */
@Component
@Slf4j
public class SmsSenderRunner implements CommandLineRunner {
    @Autowired
    SmsConfig smsConfig;

    private SmsSingleSender smsSingleSender;

    @PostConstruct
    public void init() {
        smsSingleSender = new SmsSingleSender(smsConfig.getAppid(), smsConfig.getAppkey());
    }

    @Override
    public void run(String... args) throws Exception {

        Set<String> preparePhone = PhoneGenerator.RANDOM_PHONE;
        if (!preparePhone.isEmpty()) {
            for (String phone : preparePhone) {
                try {
                    SmsSingleSenderResult result = smsSingleSender.send(smsConfig.getType(), smsConfig.getNationCode(), phone, smsConfig.getTemplateId(), "", "");
                    if (result.result == 0) {
                        // 成功投递
                        log.info("【成功投递账号】{}", phone);
                        PhoneGenerator.SEDNED_PHONE.add(phone);
                    } else if (result.result == 1031) {
                        //
                        log.error("【账号已经欠费】");
                        System.exit(-1);
                    } else {
                        log.info("【未成功投递账号】{}, errorMsg: {}", phone, result.errMsg);
                    }

                } catch (HTTPException e) {
                    // HTTP响应码错误
                } catch (JSONException e) {
                    // json解析错误
                } catch (IOException e) {
                    // 网络IO错误
                }

            }
        }
    }
}
